
import { useAppSelector } from '@/utils/hooks';
import { searchSuggestionJsonp } from '@/utils/tools/doms';
import { isNull } from 'lodash';
import { getClassNames } from 'magic-ui-react';
import { useState, useEffect, FC } from 'react';
import SearchList from '../SearchList';
import styles from './style.module.less'

/**
 * 搜索引擎联想词
 * @param props 
 * @returns SuggestionsList
 */
const SearchSuggestions: FC<{
  searchValue: string,
  absolute?: boolean,
  itemClick?: (value: string) => void,
  className?: string
}> = (props) => {
  const {
    currentSearchEngines
  } = useAppSelector((state) => state.appConfig);

  const {
    searchValue,
    absolute = false,
    itemClick,
    className
  } = props
  const [suggestions, setSuggestions] = useState([]);
  const [currentIndex, setCurrentIndex] = useState<null | number>(null);

  useEffect(() => {
    // setCurrentIndex(null)
    if (searchValue) {
      searchSuggestionJsonp(searchValue, {
        callback: (res) => {
          setSuggestions(res)
        }
      })
    } else {
      setSuggestions([])
    }
  }, [searchValue])

  const openNewTab = (search: string) => {
    window.open(`${currentSearchEngines.url}${search}`)
  }

  const keydown = (e: any) => {
    setCurrentIndex(isNull(currentIndex) ? 0 : currentIndex + 1)
    console.log(isNull(currentIndex) ? 0 : currentIndex + 1);

    if (isNull(currentIndex)) {
      if (e.code === 'ArrowUp') {
        setCurrentIndex(suggestions.length - 1)
      }
      if (e.code === 'ArrowDown') {
        setCurrentIndex(0)
      }
      console.log('currentIndex', currentIndex);
    } else {
      let newCurrentIndex = currentIndex
      if (e.code === 'ArrowUp' && newCurrentIndex > 0) {
        newCurrentIndex = newCurrentIndex - 1
      } else if (e.code === 'ArrowUp' && newCurrentIndex > 0) {
        newCurrentIndex = suggestions.length - 1
      } else if (e.code === 'ArrowDown' && newCurrentIndex < (suggestions.length - 1)) {
        newCurrentIndex = newCurrentIndex + 1
      } else if (e.code === 'ArrowDown' && newCurrentIndex === (suggestions.length - 1)) {
        newCurrentIndex = 0
      }
      console.log('newCurrentIndex', newCurrentIndex);
      setCurrentIndex(newCurrentIndex)
    }

  }

  useEffect(() => {
    // document.addEventListener('keydown', keydown)
    // document.onkeydown = keydown
  }, [])

  return (
    <>
      {
        searchValue && (
          <ol
            className={getClassNames([
              styles.SearchSuggestions,
              className,
              {
                [styles.SearchSuggestionsAbsolute]: absolute
              }
            ])}
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            <div className='px-4 pb-4'>
              <SearchList />
            </div>
            {suggestions.map((suggestion, index) => {
              return (
                <li
                  key={index}
                  className={getClassNames([
                    styles.suggestion,
                    {
                      [styles.suggestionChecked]: index === currentIndex
                    }
                  ])}
                  onClick={() => {
                    openNewTab(suggestion)
                    itemClick?.(suggestion)
                  }}
                >{suggestion}</li>
              )
            })}
          </ol>
        )
      }
    </>

  )
}
export default SearchSuggestions